package store

import (
	"codejy/globalfunc"
	"codejy/structdef"
)

func init() {
	globalfunc.RegisterFuncAll("AddTypeDefaultInstanceStore", AddTypeDefaultInstanceStore)
	globalfunc.RegisterFuncAll("GetTypeDefaultInstanceStore", GetTypeDefaultInstanceStore)
}

// 添加数据
func AddTypeDefaultInstanceStore(threadStore *structdef.ThreadStore, typeName string, instanceId string, data structdef.TypeDefault) {
	if _, ok := threadStore.TypeDefaultInstanceStore[typeName]; !ok {
		threadStore.TypeDefaultInstanceStore[typeName] = make(map[string]structdef.TypeDefault)
	}
	threadStore.TypeDefaultInstanceStore[typeName][instanceId] = data
	threadStore.TypeDefaultInstanceInversionStore[instanceId] = typeName
}

// 获取数据
func GetTypeDefaultInstanceStore(threadStore *structdef.ThreadStore, typeName string, instanceId string) structdef.TypeDefault {
	if _, ok := threadStore.TypeDefaultInstanceStore[typeName]; !ok {
		return nil
	}
	if _, ok := threadStore.TypeDefaultInstanceStore[typeName][instanceId]; !ok {
		return nil
	}
	return threadStore.TypeDefaultInstanceStore[typeName][instanceId]
}

// 删除数据
func DeleteTypeDefaultInstanceStore(threadStore *structdef.ThreadStore, typeName string, instanceId string) {
	if _, ok := threadStore.TypeDefaultInstanceStore[typeName]; !ok {
		return
	}
	if _, ok := threadStore.TypeDefaultInstanceStore[typeName][instanceId]; !ok {
		return
	}
	delete(threadStore.TypeDefaultInstanceStore[typeName], instanceId)
	delete(threadStore.TypeDefaultInstanceInversionStore, instanceId)
}

// 获取实例是否存在,和返回实例类型
func GetTypeDefaultInstanceInversionStore(threadStore *structdef.ThreadStore, instanceId string) (bool, string) {
	if _, ok := threadStore.TypeDefaultInstanceInversionStore[instanceId]; !ok {
		return false, ""
	}
	return true, threadStore.TypeDefaultInstanceInversionStore[instanceId]
}

// 通过实例id获取实例
func GetTypeDefaultInstanceStoreByInstanceId(threadStore *structdef.ThreadStore, instanceId string) structdef.TypeDefault {
	if _, ok := threadStore.TypeDefaultInstanceInversionStore[instanceId]; !ok {
		return nil
	}
	typeName := threadStore.TypeDefaultInstanceInversionStore[instanceId]
	if _, ok := threadStore.TypeDefaultInstanceStore[typeName]; !ok {
		return nil
	}
	if _, ok := threadStore.TypeDefaultInstanceStore[typeName][instanceId]; !ok {
		return nil
	}
	return threadStore.TypeDefaultInstanceStore[typeName][instanceId]
}

// 删除实例id对应的实例
func DeleteTypeDefaultInstanceStoreByInstanceId(threadStore *structdef.ThreadStore, instanceId string) {
	if _, ok := threadStore.TypeDefaultInstanceInversionStore[instanceId]; !ok {
		return
	}
	typeName := threadStore.TypeDefaultInstanceInversionStore[instanceId]
	if _, ok := threadStore.TypeDefaultInstanceStore[typeName]; !ok {
		return
	}
	if _, ok := threadStore.TypeDefaultInstanceStore[typeName][instanceId]; !ok {
		return
	}
	delete(threadStore.TypeDefaultInstanceStore[typeName], instanceId)
	delete(threadStore.TypeDefaultInstanceInversionStore, instanceId)
}
